#include "DataRecordModel.h"
#include "utils/Logger.h"
#include <QDebug>

DataRecordModel::DataRecordModel(QObject *parent)
    : QAbstractListModel(parent),
      m_maxRecords(200) // 默认保留最近 200 条数据
{
}

DataRecordModel::~DataRecordModel()
{
}

// 返回行数
int DataRecordModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    QMutexLocker locker(&m_mutex);

    // 如果设置了过滤设备，返回过滤后的数量
    if (!m_currentDeviceId.isEmpty())
    {
        return getFilteredDataPoints().count();
    }

    return m_dataQueue.count();
}

// 返回数据
QVariant DataRecordModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    QMutexLocker locker(&m_mutex);

    // 获取过滤后的数据列表
    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    if (index.row() >= dataPoints.count())
        return QVariant();

    const DataPoint &dataPoint = dataPoints.at(index.row());

    switch (role)
    {
    case IdRole:
        return dataPoint.id();
    case DeviceIdRole:
        return dataPoint.deviceId();
    case TimestampRole:
        return dataPoint.timestamp().toString("HH:mm:ss");
    case TemperatureRole:
        return dataPoint.temperature();
    case PressureRole:
        return dataPoint.pressure();
    case FlowRole:
        return dataPoint.flow();
    default:
        return QVariant();
    }
}

// 角色名称映射（QML 中使用）
QHash<int, QByteArray> DataRecordModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "dataId";
    roles[DeviceIdRole] = "deviceId";
    roles[TimestampRole] = "timestamp";
    roles[TemperatureRole] = "temperature";
    roles[PressureRole] = "pressure";
    roles[FlowRole] = "flow";
    return roles;
}

// 数据数量
int DataRecordModel::count() const
{
    QMutexLocker locker(&m_mutex);

    if (!m_currentDeviceId.isEmpty())
    {
        return getFilteredDataPoints().count();
    }

    return m_dataQueue.count();
}

// 设置最大记录数
void DataRecordModel::setMaxRecords(int maxRecords)
{
    if (m_maxRecords == maxRecords || maxRecords <= 0)
        return;

    m_maxRecords = maxRecords;
    emit maxRecordsChanged();

    // 清理超出限制的数据
    trimOldRecords();
}

// 设置当前设备 ID（过滤显示）
void DataRecordModel::setCurrentDeviceId(const QString &deviceId)
{
    if (m_currentDeviceId == deviceId)
        return;

    m_currentDeviceId = deviceId;
    emit currentDeviceIdChanged();

    // 重置模型以刷新视图
    beginResetModel();
    endResetModel();
    emit countChanged();
}

// 添加数据点（线程安全）
void DataRecordModel::addDataPoint(const DataPoint &dataPoint)
{
    if (!dataPoint.isValid())
    {
        qWarning() << "DataRecordModel: 无效的数据点";
        return;
    }

    QMutexLocker locker(&m_mutex);

    // 添加到队列尾部
    m_dataQueue.enqueue(dataPoint);

    // 移除超出限制的旧数据
    while (m_dataQueue.count() > m_maxRecords)
    {
        m_dataQueue.dequeue();
    }

    locker.unlock();

    // 通知模型更新（在主线程中执行）
    QMetaObject::invokeMethod(this, [this, dataPoint]()
                              {
        // 如果是当前设备的数据或无过滤，则刷新视图
        if (m_currentDeviceId.isEmpty() || m_currentDeviceId == dataPoint.deviceId())
        {
            beginInsertRows(QModelIndex(), rowCount(), rowCount());
            endInsertRows();
            emit countChanged();
        }

        emit dataPointAdded(dataPoint.deviceId());
        emit dataUpdated(); }, Qt::QueuedConnection);

    qDebug() << "DataRecordModel: 添加数据点 -"
             << "设备:" << dataPoint.deviceId()
             << "温度:" << dataPoint.temperature() << "℃"
             << "压力:" << dataPoint.pressure() << "kPa"
             << "流量:" << dataPoint.flow() << "L/min";
}

// 添加数据点（重载版本）
void DataRecordModel::addDataPoint(const QString &deviceId, double temperature, double pressure, double flow)
{
    DataPoint dataPoint(deviceId, temperature, pressure, flow);
    addDataPoint(dataPoint);
}

// 批量添加数据点（线程安全）
void DataRecordModel::addDataPoints(const QList<DataPoint> &dataPoints)
{
    if (dataPoints.isEmpty())
        return;

    QMutexLocker locker(&m_mutex);

    for (const DataPoint &dataPoint : dataPoints)
    {
        if (dataPoint.isValid())
        {
            m_dataQueue.enqueue(dataPoint);
        }
    }

    // 移除超出限制的旧数据
    while (m_dataQueue.count() > m_maxRecords)
    {
        m_dataQueue.dequeue();
    }

    locker.unlock();

    // 通知模型重置
    beginResetModel();
    endResetModel();
    emit countChanged();
    emit dataUpdated();

    qInfo() << "DataRecordModel: 批量添加" << dataPoints.count() << "条数据";
}

// 获取数据点
DataPoint DataRecordModel::getDataPoint(int index) const
{
    QMutexLocker locker(&m_mutex);

    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    if (index >= 0 && index < dataPoints.count())
    {
        return dataPoints.at(index);
    }

    return DataPoint();
}

// 获取最新数据点
DataPoint DataRecordModel::getLatestDataPoint() const
{
    QMutexLocker locker(&m_mutex);

    if (m_dataQueue.isEmpty())
        return DataPoint();

    return m_dataQueue.last();
}

// 获取指定设备的最新数据点
DataPoint DataRecordModel::getLatestDataPointForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    // 反向遍历查找最新数据
    for (int i = m_dataQueue.count() - 1; i >= 0; --i)
    {
        if (m_dataQueue.at(i).deviceId() == deviceId)
        {
            return m_dataQueue.at(i);
        }
    }

    return DataPoint();
}

// 获取指定设备的所有数据点
QList<DataPoint> DataRecordModel::getDataPointsForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    QList<DataPoint> result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == deviceId)
        {
            result.append(dataPoint);
        }
    }

    return result;
}

// 获取温度数据数组（用于图表）
QList<double> DataRecordModel::getTemperatureData() const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    for (const DataPoint &dataPoint : dataPoints)
    {
        result.append(dataPoint.temperature());
    }

    return result;
}

// 获取压力数据数组（用于图表）
QList<double> DataRecordModel::getPressureData() const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    for (const DataPoint &dataPoint : dataPoints)
    {
        result.append(dataPoint.pressure());
    }

    return result;
}

// 获取流量数据数组（用于图表）
QList<double> DataRecordModel::getFlowData() const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    for (const DataPoint &dataPoint : dataPoints)
    {
        result.append(dataPoint.flow());
    }

    return result;
}

// 获取时间戳数据数组（用于图表）
QStringList DataRecordModel::getTimestampData() const
{
    QMutexLocker locker(&m_mutex);

    QStringList result;
    QList<DataPoint> dataPoints = m_currentDeviceId.isEmpty()
                                      ? QList<DataPoint>(m_dataQueue.cbegin(), m_dataQueue.cend())
                                      : getFilteredDataPoints();

    for (const DataPoint &dataPoint : dataPoints)
    {
        result.append(dataPoint.timestamp().toString("HH:mm:ss"));
    }

    return result;
}

// 获取指定设备的温度数据数组
QList<double> DataRecordModel::getTemperatureDataForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == deviceId)
        {
            result.append(dataPoint.temperature());
        }
    }

    return result;
}

// 获取指定设备的压力数据数组
QList<double> DataRecordModel::getPressureDataForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == deviceId)
        {
            result.append(dataPoint.pressure());
        }
    }

    return result;
}

// 获取指定设备的流量数据数组
QList<double> DataRecordModel::getFlowDataForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    QList<double> result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == deviceId)
        {
            result.append(dataPoint.flow());
        }
    }

    return result;
}

// 获取指定设备的时间戳数据数组
QStringList DataRecordModel::getTimestampDataForDevice(const QString &deviceId) const
{
    QMutexLocker locker(&m_mutex);

    QStringList result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == deviceId)
        {
            result.append(dataPoint.timestamp().toString("HH:mm:ss"));
        }
    }

    return result;
}

// 清空数据
void DataRecordModel::clear()
{
    QMutexLocker locker(&m_mutex);

    if (m_dataQueue.isEmpty())
        return;

    beginResetModel();
    m_dataQueue.clear();
    endResetModel();

    emit countChanged();
    emit dataUpdated();

    qInfo() << "DataRecordModel: 清空所有数据";
}

// 清空指定设备的数据
void DataRecordModel::clearDeviceData(const QString &deviceId)
{
    QMutexLocker locker(&m_mutex);

    QQueue<DataPoint> newQueue;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() != deviceId)
        {
            newQueue.enqueue(dataPoint);
        }
    }

    m_dataQueue = newQueue;
    locker.unlock();

    beginResetModel();
    endResetModel();
    emit countChanged();
    emit dataUpdated();

    qInfo() << "DataRecordModel: 清空设备数据:" << deviceId;
}

// 获取过滤后的数据列表
QList<DataPoint> DataRecordModel::getFilteredDataPoints() const
{
    QList<DataPoint> result;
    for (const DataPoint &dataPoint : m_dataQueue)
    {
        if (dataPoint.deviceId() == m_currentDeviceId)
        {
            result.append(dataPoint);
        }
    }
    return result;
}

// 移除超出限制的旧数据
void DataRecordModel::trimOldRecords()
{
    QMutexLocker locker(&m_mutex);

    if (m_dataQueue.count() <= m_maxRecords)
        return;

    int removeCount = m_dataQueue.count() - m_maxRecords;
    for (int i = 0; i < removeCount; ++i)
    {
        m_dataQueue.dequeue();
    }

    locker.unlock();

    beginResetModel();
    endResetModel();
    emit countChanged();

    qInfo() << "DataRecordModel: 移除旧数据，当前数量:" << m_dataQueue.count();
}
